import axios from 'axios';
import CookiesHelper from '@/util/logintoken';
import msgHelper from '@/util/msgHelper.js'

axios.defaults.headers["Content-Type"] = "application/json";
axios.defaults.headers["Access-Control-Allow-Origin"] = "*";

const service = axios.create({
    baseURL: "http://localhost:5042",
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        //set the header if the has the isToken
        const isSetToken = (config.headers || {}).isNeedToken;
        const loginToken = CookiesHelper.getLoginToken();
        if (loginToken && isSetToken) {
            config.headers.Authorization = 'Bearer ' + loginToken;
        }
        return config;
    }

    , error => {
        console.log(error);
        return Promise.reject(error);
    });

service.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        console.log(error);
        if (error.request.status != 200) {
            if (error.request.status === 401) {
                location.href = '/login';
            }
            else {
                msgHelper.showError('失败', error.request.statusText);
            }
            console.log(error);
        }
        return Promise.reject(error);
    }
);

export default service;
